<template>
  <common-detail-list :title="`访问详情（${detailUrl}）`">
    <el-button slot="header" @click="back">返回</el-button>

    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        :model="queryParams"
        ref="queryForm"
        label-width="70px"
        @submit.native.prevent
        :inline="true"
      >
        <el-form-item label="请求体" prop="requestBody">
          <common-input
            clearable
            @enter="handleQuery"
            v-model="queryParams.requestBody"
          />
        </el-form-item>

        <el-form-item label="响应体" prop="responseBody">
          <common-input
            clearable
            @enter="handleQuery"
            v-model="queryParams.responseBody"
          />
        </el-form-item>

        <el-form-item label="识别规则" prop="dataRuleId">
          <el-select v-model="queryParams.dataRuleId" filterable>
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in querySensitiveList"
              :key="item.id"
              :label="item.ruleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数据分级" prop="dataLevelId">
          <el-select v-model="queryParams.dataLevelId" filterable>
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in queryLevelList"
              :key="item.levelId"
              :label="item.name"
              :value="item.levelId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数据分类" prop="dataTypeId">
          <el-cascader
            v-model="queryParams.dataTypeId"
            :options="dataTypeList"
            :props="cascaderProps"
            clearable
          >
            <template slot-scope="{ node, data }">
              <common-carousel-text
                :content="data.typeName"
              ></common-carousel-text>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="重要数据" prop="dataTagId">
          <el-cascader
            class="custom-cascader-style"
            style="width: 100%"
            :options="importData"
            v-model="queryParams.dataTagId"
            :show-all-levels="false"
            :props="importDataProps"
            checkStrictly
            clearable
            :append-to-body="false"
          >
            <template slot-scope="{ node, data }">
              <common-marquee-text
                :content="data.typeName"
              ></common-marquee-text>
            </template>
          </el-cascader>
        </el-form-item>

        <el-form-item label="核心数据" prop="dataCoreId">
          <el-cascader
            class="custom-cascader-style"
            style="width: 100%"
            :options="coreData"
            v-model="queryParams.dataCoreId"
            :show-all-levels="false"
            :props="coreDataProps"
            checkStrictly
            clearable
            :append-to-body="false"
          >
            <template slot-scope="{ node, data }">
              <common-marquee-text
                :content="data.typeName"
              ></common-marquee-text>
            </template>
          </el-cascader>
        </el-form-item>

        <el-form-item label="URL" prop="apiUrl">
          <common-input
            clearable
            @enter="handleQuery"
            v-model="queryParams.apiUrl"
          />
        </el-form-item>

        <el-form-item label="日期">
          <el-date-picker
            v-model="date"
            type="datetimerange"
            @change="dateChange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </common-search>

    <el-row slot="tools">
      <el-col :span="1.5">
        <el-switch
          style="margin-bottom: 16px; margin-left: 18px"
          v-model="queryParams.isSensitiveData"
          @change="handleQuery"
          active-value="1"
          :inactive-value="null"
          active-color="#13ce66"
          inactive-color="#909399"
          active-text="仅含有敏感数据"
          inactive-text="所有数据"
        >
        </el-switch>
      </el-col>
      <el-col :span="1.5">
        <el-switch
          style="margin-bottom: 16px; margin-left: 18px"
          v-model="queryParams.isDataTag"
          @change="handleQuery"
          active-value="1"
          :inactive-value="null"
          active-color="#13ce66"
          inactive-color="#909399"
          active-text="仅含有重要数据"
          inactive-text="所有数据"
        >
        </el-switch>
      </el-col>
    </el-row>

    <common-list
      slot="content"
      v-loading="loading"
      :style="{ height: total === 0 ? '0' : '' }"
    >
      <el-row class="url-detail">
        <el-col
          :span="8"
          class="url-detail-containner"
          v-for="(item, index) in urlDetailList"
          :key="index"
        >
          <div class="detail-title">
            <div class="url-detail-time">
              {{ item.createTime }}
            </div>
            <div class="url-detail-url">
              <el-popover placement="top-start" trigger="hover">
                <div>{{ item.url }}</div>
                <div slot="reference" class="url-value">{{ item.url }}</div>
              </el-popover>
            </div>
          </div>

          <div class="url-detail-content">
            <common-tabs
              slot="tabs"
              v-model="item.activeName"
              @tab-click="tabChange"
            >
              <el-tab-pane label="请求头" name="requestHeaders">
                <common-json-view
                  v-if="item.requestHeaders && isJSON(item.requestHeaders)"
                  :json="JSON.parse(item.requestHeaders)"
                ></common-json-view>
                <div v-else>{{ item.requestHeaders }}</div>
              </el-tab-pane>
              <el-tab-pane label="请求体" name="requestBody"
                ><common-json-view
                  v-if="item.requestBody && isJSON(item.requestBody)"
                  :json="JSON.parse(item.requestBody)"
                ></common-json-view>
                <div v-else>{{ item.requestBody }}</div>
              </el-tab-pane>
              <el-tab-pane label="响应头" name="responseHeaders"
                ><common-json-view
                  v-if="item.responseHeaders && isJSON(item.responseHeaders)"
                  :json="JSON.parse(item.responseHeaders)"
                ></common-json-view>
                <div v-else>{{ item.responseHeaders }}</div></el-tab-pane
              >
              <el-tab-pane label="响应体" name="responseBody"
                ><common-json-view
                  v-if="item.responseBody && isJSON(item.responseBody)"
                  :json="JSON.parse(item.responseBody)"
                ></common-json-view>
                <div v-else>{{ item.responseBody }}</div></el-tab-pane
              >

              <el-tab-pane label="敏感详情" name="responseSensitive">
                <el-form label-width="80px" v-model="item.sensitiveDetail">
                  <el-row>
                    <el-col :span="24"
                      ><el-form-item
                        label="识别规则："
                        prop="interfaceSensitiveRule"
                      >
                        <span style="color: #fd0000">
                          {{
                            item.sensitiveDetail.interfaceSensitiveRule
                          }}</span
                        ></el-form-item
                      ></el-col
                    >
                  </el-row>

                  <el-row>
                    <el-col :span="24"
                      ><el-form-item
                        label="数据分级："
                        prop="interfaceDataLevel"
                      >
                        {{
                          item.sensitiveDetail.interfaceDataLevel
                        }}</el-form-item
                      ></el-col
                    >
                  </el-row>

                  <el-row>
                    <el-col :span="24"
                      ><el-form-item
                        label="数据分类："
                        prop="interfaceDataType"
                      >
                        {{
                          item.sensitiveDetail.interfaceDataType
                        }}</el-form-item
                      ></el-col
                    >
                  </el-row>

                  <el-row>
                    <el-col :span="24"
                      ><el-form-item label="重要数据：" prop="interfaceDataTag">
                        {{
                          item.sensitiveDetail.interfaceDataTag
                        }}</el-form-item
                      ></el-col
                    >
                  </el-row>

                  <el-row>
                    <el-col :span="24"
                      ><el-form-item
                        label="核心数据："
                        prop="interfaceCoreData"
                      >
                        {{
                          item.sensitiveDetail.interfaceCoreData
                        }}</el-form-item
                      ></el-col
                    >
                  </el-row>
                </el-form>
              </el-tab-pane>
            </common-tabs>
          </div>
        </el-col>
      </el-row>
    </common-list>

    <common-empty-data
      v-if="total === 0 && fetchFinished"
      slot="content"
    ></common-empty-data>
    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :pageSizes="[9, 18, 27, 36]"
      @pagination="getList"
    />
  </common-detail-list>
</template>

<script>
import {
  querySensitiveList,
  queryDataTypeTreeList,
  queryTagList,
  queryLevelList,
} from "@/api/apisecurity/apiinterface/interface";
import { fetchDetailList } from "@/api/apisecurity/accesssource/accesssource.js";
import { parseTime } from "@/utils/ruoyi";
import { isJSON } from "@/utils/util";
import * as iAPI from "@/api/datascan/importdata";
import * as cAPI from "@/api/datascan/coredata";
import { queryList } from "@/api/datahandler/discernRule";

export default {
  data() {
    let now = parseTime(new Date());
    let start = `${parseTime(new Date(new Date().setHours(0, 0, 0, 0)))}`;
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 9,
        startTime: start,
        endTime: now,
        requestBody: null,
        responseBody: null,
        sensitiveDataId: null,
        dataLevelId: null,
        dataTagId: null,
        levelId: null,
        dataCoreId: null,
        dataRuleId: null,
      },
      cascaderProps: {
        label: "typeName",
        value: "typeId",
        emitPath: false,
      },

      total: 0,
      urlDetailList: [],
      date: [start, now],
      detailShow: false,
      loading: false,
      fetchFinished: false,
      queryLevelList: [],
      queryTagList: [],
      dataTypeList: [],
      querySensitiveList: [],

      coreData: [],
      importData: [],
      importDataProps: {
        label: "typeName",
        value: "typeId",
        emitPath: false,
      },
      coreDataProps: {
        label: "typeName",
        value: "typeId",
        emitPath: false,
      },
    };
  },

  props: {
    detailUrl: {
      type: String,
      default: "",
    },
  },

  created() {
    this.getList();
    this.querySensitive();
    this.getDataTypeList();
    // this.queryTag();
    this.queryLevel();
    this.getCoreDataList();
    this.getImportDataList();
  },
  methods: {
    //数据分级
    queryLevel() {
      queryLevelList().then((res) => {
        if (res && res.code === 200) {
          this.queryLevelList = res.data.data;
        } else {
          this.queryLevelList = [];
        }
      });
    },
    //获取核心数据
    getCoreDataList() {
      cAPI.queryTreeList().then((res) => {
        if (res && res.code === 200) {
          this.coreData = res.data;
        } else {
          this.coreData = [];
        }
      });
    },
    //获取重要数据
    getImportDataList() {
      iAPI.queryTreeList().then((res) => {
        if (res && res.code === 200) {
          this.importData = res.data;
        } else {
          this.importData = [];
        }
      });
    },
    //数据分类
    getDataTypeList() {
      queryDataTypeTreeList().then((res) => {
        if (res && res.code === 200) {
          this.dataTypeList = res.data.data;
        } else {
          this.dataTypeList = [];
        }
      });
    },
    //识别规则
    querySensitive() {
      queryList({ status: 0 }).then((res) => {
        if (res && res.code === 200) {
          this.querySensitiveList = res.rows;
        } else {
          this.querySensitiveList = [];
        }
      });
    },
    // //敏感字段
    // querySensitive() {
    //   querySensitiveList().then((res) => {
    //     if (res && res.code === 200) {
    //       this.querySensitiveList = res.data.data;
    //     } else {
    //       this.querySensitiveList = [];
    //     }
    //   });
    // },

    isJSON(str) {
      return isJSON(str);
    },
    tabChange() {},
    back() {
      this.$emit("back");
    },

    handleQuery() {
      if (this.date && this.date.length > 0) {
        this.queryParams.startTime = this.date[0];
        this.queryParams.endTime = this.date[1];
      } else {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      let now = parseTime(new Date());
      let start = `${parseTime(new Date(new Date().setHours(0, 0, 0, 0)))}`;
      this.date = [start, now];
      this.queryParams = this.$options.data().queryParams;
    },

    dateChange() {
      let endTime = null,
        startTime = null;
      if (this.date && this.date.length > 0) {
        startTime = this.date[0];
        endTime = this.date[1];
      }
      this.queryParams.startTime = startTime || null;
      this.queryParams.endTime = endTime || null;
    },

    getList() {
      this.loading = true;
      fetchDetailList(
        Object.assign({}, this.queryParams, { ip: this.detailUrl })
      )
        .then((res) => {
          if (res && res.code === 200) {
            this.urlDetailList = res.rows;
            this.total = res.total;
            this.urlDetailList.forEach((item) => {
              item.activeName = "requestHeaders";
              item.sensitiveDetail = {
                interfaceSensitiveData: item.interfaceSensitiveData,
                interfaceDataLevel: item.interfaceDataLevel,
                interfaceDataType: item.interfaceDataType,
                interfaceDataTag: item.interfaceDataTag,
                interfaceCoreData: item.interfaceCoreData,
                interfaceSensitiveRule: item.interfaceSensitiveRule,
              };
            });
            this.fetchFinished = true;
          } else {
            this.urlDetailList = [];
            this.total = 0;
          }
        })
        .catch(() => {
          this.urlDetailList = [];
          this.total = 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.url-detail {
  .url-detail-containner {
    height: 400px;
    margin-right: 10px;
    margin-bottom: 10px;

    background-color: #fff;
    padding: 10px 0;
    border-radius: 4px;

    .detail-title {
      width: 100%;
      font-size: 14px;
      display: flex;
      justify-content: space-between;
    }
    .url-detail-time {
      height: 25px;
      padding: 0 10px;
      min-width: 160px;
    }
    .url-detail-url {
      width: calc(100% - 180px);
      margin-right: 10px;
      .url-value {
        width: 100%;
        text-align: right;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
    .url-detail-content {
      border-top: 1px #eee solid;
      ::v-deep .el-tabs__content {
        font-size: 13px;
        overflow-y: scroll;
        padding: 10px;
        height: 320px;
        word-break: break-all;
      }
      ::v-deep .el-tabs__item {
        font-size: 13px;
      }
      ::v-deep .el-tabs__nav {
        margin-left: 10px;
      }
    }
  }
  .el-col-8 {
    width: 32.5%;
    border: 1px #eee solid;
  }
}

::v-deep .global-common-list-template-container {
  overflow-y: scroll;
}

::v-deep .global-base-list-container {
  padding: 0 0 18px 18px;
}

::v-deep .common-json-view-wrap {
  box-shadow: none;
}
</style>
